﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using MediaController.Extractor;
using MediaController.Utils.Listener;

namespace MediaController.Watcher
{
    public class AutoExtractWatchFolder : WatchFolder
    {
        readonly object _syncObject = new object();

        public bool MoveExtractFile { get; set; }

        public bool MoveWithDirectory { get; set; }

        public string Destination { get; set; }

        public int Depth { get; set; }

        public string Exexute { get; set; }

        public event Action<string> FileFouned;

        public event Action<string> ExtractCompleted;

        public AutoExtractWatchFolder(string watchPath)
            : base(watchPath)
        { }

        protected override void OnFolderListenerFileReceived(FolderListener folderListener, ReceivedFileInfo receivedFileInfo)
        {
            lock (_syncObject)
            {
                receivedFileInfo.DeleteOnComplete = false;

                string destination = !string.IsNullOrEmpty(Destination) ? Destination : Path.GetDirectoryName(receivedFileInfo.FullName);
                var dirInfo = new DirectoryInfo(Path.GetDirectoryName(receivedFileInfo.FullName));
                if (destination.Contains("Extractor.Done"))
                {
                    return;
                }

                var archiveCollection = new ArchiveCollection();
                archiveCollection.Source = dirInfo;
                if (archiveCollection.Archives.Count > 0)
                {
                    InvokeFileFouned(receivedFileInfo.FullName);

                    archiveCollection.Destination = dirInfo;
                    archiveCollection.Process();

                    Directory.Move(destination, string.Format("{0}.{1}", destination, "Extractor.Done"));

                    InvokeExtractCompleted(receivedFileInfo.FullName);
                    folderListener.Stop();
                }
            }
        }

        private void InvokeFileFouned(string fileName)
        {
            Action<string> handler = FileFouned;
            if (handler != null) handler(fileName);
        }

        private void InvokeExtractCompleted(string fileName)
        {
            Action<string> handler = ExtractCompleted;
            if (handler != null) handler(fileName);
        }

    }
}
